package util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

/**
 * Created by WF on 2019/9/23 10:32
 */
@Data
@ConfigurationProperties(prefix = "jwt")
public class JwtUtil {
    private String key;         //签名的key
    private long ttl;           //过期时间

    //1.生成token
    public String createJwt(String id,String subject,String roles){
        //1.1)创建jwtBuilder生成器对象
        long l = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .signWith(SignatureAlgorithm.HS256, key)
                .setIssuedAt(new Date(l))
                .setSubject(subject)
                .claim("roles",roles);
        //1.2)判断是否存在过期时间
        System.out.println("ttl:" + ttl);
        System.out.println("key:" + key);
         if(ttl > 0){
             jwtBuilder.setExpiration(new Date(l + ttl));
         }
         //1.3)返回生成的token
        return jwtBuilder.compact();
    }
    //2.解析token
    public Claims parseJwt(String token){
        //2.1)生成claimsJws对象
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key)
                .parseClaimsJws(token);
        //2.2)得到解析的主体对象claims
        Claims claims = claimsJws.getBody();
        //2.3）返回
        return claims;
    }

}
